package com.fafu.utils;





import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBManger {
    private static String driverClassName;
    private static String url;
    private static String username;
    private static String password;
    private static Connection connection;
    static {
        InputStream is = DBManger.class .getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
            driverClassName = properties.getProperty("driverClassName");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            System.out.println(driverClassName+url+username+password);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    // 第一次启动DBManger时候执行的代码

    public static Connection getConnection(){
        //加载驱动
        try {
            if(connection==null){//确保全局唯一的connnection
                Class.forName("com.mysql.cj.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/student?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=UTF-8","root","root");
            }
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeConnnection(ResultSet resultSet,PreparedStatement pstm,Connection connection){
        try {
            connection.close();
            resultSet.close();
            pstm.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //增删改通用方案
    public static int executeUpdate(String sql,Object...param){
        try {
            PreparedStatement pstm = getConnection().prepareStatement(sql);
            if(param!=null){
                for(int i = 0;i < param.length;i++){
                    pstm.setObject((i+1),param[i]);
                }
            }
            return pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }
}
